//
//  AY_ReadBookTool.m
//  AiYue
//
//  Created by 小二同學 on 2025/1/4.
//

#import "AY_ReadBookTool.h"

static AVSpeechSynthesizer *_synthesizer;
static AVSpeechUtterance *_utterance;
static float _speedIndex;
static BOOL _isWorking;
@implementation AY_ReadBookTool

+ (AVSpeechSynthesizer *)getManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _isWorking = NO;
        _synthesizer = [[AVSpeechSynthesizer alloc] init];
    });
    return _synthesizer;
}

+ (BOOL)getWorkStatus {
    return _isWorking;
}

+ (void)speakText:(NSString *)text {
    if (_isWorking) {
        return;
    }
    _utterance = nil;
    [AY_ReadBookTool stopSpeak];
    _utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    NSString *speedStr = [AYMMKV getStringForKey:SPEEDINDEX defaultValue:@"2"];
    if ([speedStr isEqualToString:@"2"]) {
        speedStr = @"2.5";
    }
    _speedIndex = ((speedStr.intValue + 1) * 0.2) - 0.1;
    _utterance.rate = _speedIndex; // 语速，范围0.0~1.0
    _utterance.pitchMultiplier = 1.0; // 音高，范围0.5~2.0
    _utterance.postUtteranceDelay = 0.1f;
    _utterance.volume = 1.0; // 音量，范围0.0~1.0
    //设置发音，这是中文普通话
     AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    _utterance.voice = voice;
    //开始播放
//    AVSpeechSynthesizer *avSpeech = [[AVSpeechSynthesizer alloc] init];
//     [avSpeech speakUtterance:_utterance];
    [_synthesizer speakUtterance:_utterance];
    //后台播放
   [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
   //静音状态下播放
   [[AVAudioSession sharedInstance] setActive:YES error:nil];
    _isWorking = YES;
}

+ (void)stopSpeak {
    [AY_ReadBookTool pauseSpeak];
    [_synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
    _isWorking = NO;
}

+ (void)pauseSpeak {
    [_synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
    _isWorking = NO;
}

+ (void)continueSpeak {
    [_synthesizer continueSpeaking];
    _isWorking = YES;
}

+ (void)setYinSe:(NSInteger)index {
    _utterance.pitchMultiplier = index;
}
@end
